<template>
  <a-modal
    :visible="visible"
    title="订阅战队"
    width="800px"
    :maskClosable="false"
    @ok="handleSubscribe"
    @cancel="handleCancel"
    ok-text="确认订阅"
    cancel-text="取消"
    :body-style="{ padding: '32px', overflow: 'hidden' }"
    :confirm-loading="subscribing"
  >
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <a-spin size="large" />
      <p>加载战队信息中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-icon">
        <i class="fa fa-exclamation-circle"></i>
      </div>
      <p class="error-message">{{ error }}</p>
      <a-button type="primary" @click="fetchTeamData">重试</a-button>
    </div>

    <!-- 正常内容（使用接口数据） -->
    <div v-else class="subscribe-modal-content">
      <!-- 战队信息摘要 -->
      <div class="team-summary mb-8">
        <div class="team-header">
          <img
            :src="getTeamLogoUrl(teamData.logo)"
            alt="战队Logo"
            class="team-logo"
            @error="handleImageError"
          >
          <div class="team-info">
            <h3 class="team-name">{{ teamData.teamName }}</h3>
            <p class="team-desc">{{ teamData.description }}</p>
          </div>
        </div>
      </div>

      <!-- 订阅套餐信息 -->
      <div class="subscription-plan">
        <h4 class="plan-title">订阅详情</h4>

        <div class="plan-details">
          <div class="plan-item">
            <span class="plan-label">订阅价格：</span>
            <span class="plan-value">¥{{ teamData.subscribePrice || 0 }}/{{ getCycleText(teamData.subscribeCycle || 0) }}</span>
          </div>

          <div class="plan-item">
            <span class="plan-label">积分价格：</span>
            <span class="plan-value">{{ getPointsPrice() }}积分/{{ getCycleText(teamData.subscribeCycle || 0) }}</span>
          </div>

          <div class="plan-item">
            <span class="plan-label">折扣：</span>
            <span class="plan-value">{{ teamData.subscribeDiscount ? (teamData.subscribeDiscount * 10) + '折' : '无折扣' }}</span>
          </div>

          <div class="plan-item">
            <span class="plan-label">试用天数：</span>
            <span class="plan-value">{{ teamData.trialDays || 0 }}天</span>
          </div>

          <div class="plan-item">
            <span class="plan-label">自动续费：</span>
            <span class="plan-value">{{ teamData.autoRenew === 1 ? '是' : '否' }}</span>
          </div>

          <div class="plan-item">
            <span class="plan-label">当前订阅人数：</span>
            <span class="plan-value">{{ teamData.currentCount || 0 }}/{{ teamData.maxCount || 0 }}人</span>
          </div>

          <!-- 用户积分信息 -->
          <div class="plan-item user-points-info">
            <span class="plan-label">我的积分：</span>
            <span class="plan-value points-value">{{ userPoints }}积分</span>
          </div>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div class="payment-method mt-8">
        <h4 class="payment-title">选择支付方式</h4>
        <div class="payment-options">
          <label class="payment-option" @click="selectPayment('alipay')">
            <input type="radio" name="payment" value="alipay" class="payment-radio" :checked="selectedPayment === 'alipay'">
            <span class="payment-icon alipay-icon">
              <i class="fa fa-credit-card"></i>
            </span>
            <span class="payment-name">支付宝</span>
          </label>
          
          <label class="payment-option" @click="selectPayment('points')">
            <input type="radio" name="payment" value="points" class="payment-radio" :checked="selectedPayment === 'points'">
            <span class="payment-icon points-icon">
              <i class="fa fa-coins"></i>
            </span>
            <span class="payment-name">积分支付</span>
            <span class="payment-hint" v-if="selectedPayment === 'points'">
              (需{{ getPointsPrice() }}积分)
            </span>
          </label>
        </div>
      </div>

      <!-- 支付宝二维码区域 -->
      <div v-if="selectedPayment === 'alipay'" class="alipay-qr-container">
        <div v-if="generatingQrCode" class="qr-loading">
          <a-spin size="large" />
          <p>正在生成支付二维码...</p>
        </div>
        <div v-else-if="qrCodeBase64" class="qr-code-wrapper">
          <img
            :src="qrCodeBase64"
            alt="支付宝支付二维码"
            class="alipay-qr-code"
            @error="handleQrCodeError"
          >
          <p class="qr-hint">请使用支付宝扫描二维码完成支付</p>
        </div>
      </div>

      <!-- 积分支付确认区域 -->
      <div v-if="selectedPayment === 'points'" class="points-payment-container">
        <div class="points-payment-info">
          <div class="points-summary">
            <div class="points-item">
              <span class="points-label">所需积分：</span>
              <span class="points-value required">{{ getPointsPrice() }}积分</span>
            </div>
            <div class="points-item">
              <span class="points-label">我的积分：</span>
              <span class="points-value" :class="{ 'insufficient': userPoints < getPointsPrice() }">{{ userPoints }}积分</span>
            </div>
            <div class="points-item" v-if="userPoints < getPointsPrice()">
              <span class="points-label">积分不足：</span>
              <span class="points-value insufficient">还差{{ getPointsPrice() - userPoints }}积分</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted } from 'vue'
import { message } from 'ant-design-vue';
import { subscribeTeam } from '@/api/sysSubscriptionController';
import { subscribeTask, getUserPointsRecord } from '@/api/taskActionController';
import { getMinioUrl, config } from '@/utils/config';
import { useTeamStore } from '@/stores/teamStore.ts'
import { createOrder } from '@/api/bizOrderController.ts'

// 定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

// 定义组件事件
const emit = defineEmits(['update:visible', 'onSubscribe', 'onError']);

// 状态管理
const teamData = ref({});
const loading = ref(false);
const error = ref('');
const subscribing = ref(false);
const teamStore = useTeamStore()

// 支付相关状态
const selectedPayment = ref(''); // 选中的支付方式：'alipay' 或 'points'
const generatingQrCode = ref(false); // 生成二维码中
const qrCodeBase64 = ref(''); // 二维码Base64
const orderId = ref(''); // 订单ID

// 用户积分信息
const userPoints = ref(0);

// 获取用户积分
const fetchUserPoints = async () => {
  try {
    const response = await getUserPointsRecord();
    if (response.data.code === 0) {
      userPoints.value = response.data.data?.points || 0;
    }
  } catch (err) {
    console.error('获取用户积分失败:', err);
    userPoints.value = 0;
  }
};

// 获取战队数据
const fetchTeamData = async () => {
  loading.value = true;
  error.value = '';
  try {
    teamData.value = teamStore.teamDetails;
    if (!teamData.value) {
      throw new Error('未获取到有效的战队信息');
    }
    // 同时获取用户积分
    await fetchUserPoints();
    loading.value = false;
  } catch (err) {
    error.value = err.message || '加载战队信息失败';
    loading.value = false;
    emit('onError', error.value);
  }
};

// 选择支付方式
const selectPayment = async (paymentType) => {
  selectedPayment.value = paymentType;

  // 如果选择支付宝且还没有生成二维码，调用接口生成
  if (paymentType === 'alipay' && !qrCodeBase64.value) {
    await generateAlipayQrCode();
  }
};

// 生成支付宝二维码
const generateAlipayQrCode = async () => {
  if (!teamData.value?.id) {
    message.warning('请先加载战队信息');
    return;
  }

  generatingQrCode.value = true;
  try {
    // 获取当前登录用户ID
    const userId = JSON.parse(localStorage.getItem("userInfo")).userId
    if (!userId) {
      throw new Error('请先登录');
    }

    // 调用创建订单接口
    const response = await createOrder({
      teamId: teamData.value.id,
      userId: userId,
      amount: teamData.value.subscribePrice || 0,
      goodsIds: teamData.value.id,
      orderType: 1
    });

    if (response.data.code === 0) {
      // 根据实际接口返回结构调整
      const orderData = response.data.data || response.data;
      qrCodeBase64.value = orderData.qrCodeBase64 || orderData.qrCode;
      orderId.value = orderData.id || '';

      if (!qrCodeBase64.value) {
        throw new Error('未获取到支付二维码');
      }
    } else {
      throw new Error(response.data.message || '生成二维码失败');
    }
  } catch (err) {
    message.error(err.message || '生成二维码失败，请重试');
    qrCodeBase64.value = '';
  } finally {
    generatingQrCode.value = false;
  }
};

// 计算积分价格（假设1元=10积分）
const getPointsPrice = () => {
  const price = teamData.value.subscribePrice || 0;
  return Math.ceil(price * 10); // 向上取整
};

// 处理订阅
const handleSubscribe = async () => {
  if (!selectedPayment.value) {
    message.warning('请先选择支付方式');
    return;
  }

  if (selectedPayment.value === 'points') {
    // 积分支付
    if (userPoints.value < getPointsPrice()) {
      message.warning('积分不足，无法订阅');
      return;
    }

    subscribing.value = true;
    try {
      const userId = JSON.parse(localStorage.getItem("userInfo")).userId;
      if (!userId) {
        throw new Error('请先登录');
      }

      // 调用积分订阅接口
      const response = await subscribeTask({
        teamId: teamData.value.id,
        userId: userId,
        points: getPointsPrice()
      });

      if (response.data.code === 0) {
        message.success('积分订阅成功！即将为您开通战队专属权益');
        emit('update:visible', false);
        emit('onSubscribe', {
          teamId: teamData.value.id,
          paymentMethod: 'points',
          points: getPointsPrice(),
          result: response.data.data
        });
      } else {
        throw new Error(response.data.data || '积分订阅失败');
      }
    } catch (err) {
      message.error(err.message || '积分订阅失败，请重试');
    } finally {
      subscribing.value = false;
    }
    return;
  }

  if (selectedPayment.value === 'alipay' && !qrCodeBase64.value) {
    message.warning('请先选择支付宝并生成支付二维码');
    return;
  }

  subscribing.value = true;
  try {
    const userId = JSON.parse(localStorage.getItem("userInfo")).userId;
    if (!userId) {
      throw new Error('请先登录');
    }

    const response = await subscribeTeam({
      teamId: teamData.value.id,
      userId: userId,
      paymentMethod: 'alipay',
      price: teamData.value.subscribePrice || 0
    });

    if (response.data.code === 0) {
      message.success('订阅成功！即将为您开通战队专属权益');
      emit('update:visible', false);
      emit('onSubscribe', {
        teamId: teamData.value.id,
        paymentMethod: 'alipay',
        price: teamData.value.subscribePrice || 0,
        result: response.data.data
      });
    } else {
      throw new Error(response.data.message || '订阅失败');
    }
  } catch (err) {
    message.error(err.message || '订阅失败，请重试');
  } finally {
    subscribing.value = false;
  }
};

// 处理取消
const handleCancel = () => {
  // 重置状态
  selectedPayment.value = '';
  qrCodeBase64.value = '';
  orderId.value = '';
  emit('update:visible', false);
};

// 格式化周期文本
const getCycleText = (cycle) => {
  const cycleMap = {
    0: '一次性',
    1: '周',
    2: '月',
    3: '季',
    4: '年'
  };
  return cycleMap[cycle] || '未知';
};

// 获取战队Logo URL
const getTeamLogoUrl = (logo) => {
  if (!logo) return config.image.defaultLogo;
  return getMinioUrl(logo) || config.image.defaultLogo;
};

// 图片加载错误处理
const handleImageError = (event) => {
  const img = event.target;
  img.src = config.image.defaultLogo;
};

// 二维码加载错误处理
const handleQrCodeError = (event) => {
  const img = event.target;
  message.error('二维码加载失败，请重试');
  qrCodeBase64.value = '';
};

onMounted(() => {
  fetchTeamData();
})
</script>

<style scoped>
/* 保留你原有的所有样式，未做任何修改 */
.subscribe-modal-content {
  max-height: none;
  overflow: visible;
  padding: 8px 0;
}

.loading-container {
  text-align: center;
  padding: 60px 0;
}

.loading-container p {
  margin-top: 16px;
  color: #666;
}

.error-container {
  text-align: center;
  padding: 40px 20px;
}

.error-icon {
  font-size: 48px;
  color: #ff4d4f;
  margin-bottom: 16px;
}

.error-message {
  color: #666;
  margin-bottom: 24px;
  font-size: 16px;
}

.team-summary {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.team-header {
  display: flex;
  align-items: center;
}

.team-logo {
  width: 100px;
  height: 100px;
  border-radius: 12px;
  object-fit: cover;
  margin-right: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.team-info .team-name {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.team-info .team-desc {
  color: #666;
  font-size: 16px;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.plan-title, .payment-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
  padding-left: 4px;
}

.plan-details {
  background-color: #f9fafb;
  border-radius: 12px;
  padding: 20px;
}

.plan-item {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
}

.plan-label {
  width: 140px;
  color: #666;
  flex-shrink: 0;
  font-size: 16px;
}

.plan-value {
  color: #333;
  flex-grow: 1;
  font-size: 16px;
}

.user-points-info {
  background-color: #e6f7ff;
  border-radius: 8px;
  padding: 12px;
  margin-top: 16px;
}

.points-value {
  color: #1890ff;
  font-weight: bold;
}

.payment-method {
  margin-top: 24px;
}

.payment-options {
  display: flex;
  gap: 20px;
  margin-top: 12px;
  flex-wrap: wrap;
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border: 1px solid #ddd;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 150px;
  position: relative;
}

.payment-option:hover {
  border-color: #1890ff;
  background-color: #f0f7ff;
}

.payment-radio {
  display: none;
}

.payment-option:has(.payment-radio:checked) {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.payment-option:has(.payment-radio:checked) .payment-name {
  color: #1890ff;
}

.payment-icon {
  font-size: 24px;
  margin-right: 12px;
}

.alipay-icon {
  color: #1677FF;
}

.points-icon {
  color: #faad14;
}

.payment-name {
  font-size: 16px;
  color: #333;
}

.payment-hint {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}

/* 二维码区域样式（保持原有风格） */
.alipay-qr-container {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  text-align: center;
}

.qr-loading {
  padding: 30px 0;
}

.qr-code-wrapper {
  padding: 10px 0;
}

.alipay-qr-code {
  width: 200px;
  height: 200px;
  object-fit: contain;
  margin: 0 auto;
  background: #fff;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.qr-hint {
  margin-top: 15px;
  color: #666;
  font-size: 14px;
}

/* 积分支付区域样式 */
.points-payment-container {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background-color: #fafafa;
}

.points-payment-info {
  text-align: center;
}

.points-summary {
  margin-bottom: 20px;
}

.points-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
}

.points-label {
  color: #666;
  font-size: 16px;
}

.points-value {
  font-size: 16px;
  font-weight: bold;
}

.points-value.required {
  color: #faad14;
}

.points-value.insufficient {
  color: #ff4d4f;
}
</style>
